package com.pengtu.gsj.service.impl.yh;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.pengtu.gsj.dao.base.Page;
import com.pengtu.gsj.dao.base.QueryFilter;
import com.pengtu.gsj.dao.base.QueryFilter.MatchType;
import com.pengtu.gsj.dao.yh.MainBulletinDao;
import com.pengtu.gsj.entity.app.Attachment;
import com.pengtu.gsj.entity.check.CheckProject;
import com.pengtu.gsj.entity.check.CheckTable;
import com.pengtu.gsj.entity.yh.MainBulletin;
import com.pengtu.gsj.service.check.CheckTableService;
import com.pengtu.gsj.service.system.SystemManageService;
import com.pengtu.gsj.service.yh.MainBulletinService;
import com.pengtu.gsj.utils.DateUtils;
import com.pengtu.gsj.utils.MathsUtils;

@Transactional
@Service
public class MainBulletinServiceImpl implements MainBulletinService {
	
	private static Logger logger = Logger.getLogger(MainBulletinServiceImpl.class);

	@Autowired
	private MainBulletinDao mainBulletinDao;
	@Autowired
	private SystemManageService systemManageService;
	@Autowired
	private CheckTableService checkTableService;

	@Override
	public MainBulletin getMainBulletinById(String id) {
		return mainBulletinDao.get(id);
	}

	@Override
	public void deleteMainBullentin(MainBulletin mainBulletin) {
		if (mainBulletin.getAttachments() != null) {
			for (Attachment attachment : mainBulletin.getAttachments()) {
				systemManageService.deleteAttachment(attachment);
			}
		}
		mainBulletinDao.delete(mainBulletin);
	}

	@Override
	public Page<MainBulletin> findMainBulletin(Page<MainBulletin> page,
			QueryFilter queryFilter) {
		return mainBulletinDao.findPage(page, queryFilter);
	}

	@Override
	public void saveMainBulletin(MainBulletin mainBulletin) {
		mainBulletinDao.save(mainBulletin);
	}

	@Override
	public List<MainBulletin> getMainBulletinsGroupByManageOrg() {
		return mainBulletinDao.getMainBulletinsByManageOrg();
	}

	@Override
	public List<MainBulletin> getAllMainBulletins() {
		return mainBulletinDao.getAll();
	}

	@Override
	public List<MainBulletin> getMainBulletinsByManageOrg(String manageOrg) {
		return mainBulletinDao.findBy("manageOrg", manageOrg);
	}

	@Override
	public List<MainBulletin> getMainBulletins(QueryFilter queryFilter) {
		return mainBulletinDao.find(queryFilter, "bullentinYear", true);
	}

	@Override
	public Map<String, Object> getCheckMainBulletins(CheckProject checkProject, CheckTable checkTable) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		if (checkProject == null || checkTable == null) {
			logger.info("参数不能为空");
			return map;
		}
		
		List<MainBulletin> mainBulletins  = new ArrayList<MainBulletin>();
		List<Object> values = new ArrayList<Object>();
		
		JSONObject jsonObject = JSONObject.parseObject(checkTable.getRetrieval());
		double yearFull = Double.parseDouble((String)jsonObject.get("yearFull"));
		double yearPart = Double.parseDouble((String)jsonObject.get("yearPart"));
		
		String manageOrg = (String)jsonObject.get("manageOrg");
		QueryFilter queryFilter = new QueryFilter();
		queryFilter.addFilter("bullentinYear", checkProject.getStartTime()+"-01", MatchType.GE);
		queryFilter.addFilter("bullentinYear", checkProject.getEndTime()+"-12", MatchType.LE);
		
		int yearLength = Integer.parseInt(checkProject.getEndTime()) - Integer.parseInt(checkProject.getStartTime()) + 1;
		String[] timeData = DateUtils.getHalfYear(checkProject.getEndTime(), checkProject.getStartTime());
		List<String> timeResult = new ArrayList<String>(yearLength*2);
		List<Integer> years = new ArrayList<Integer>();
		
		double total =0; //检查得分
		double percentage =0; //系统完善度
		double tableFull = yearFull*4*yearLength;
		
		for (int i = 0; i < yearLength; i++) {
			years.add(Integer.parseInt(checkProject.getStartTime())+i);
		}
		
		if (StringUtils.isEmpty(manageOrg)) {
			mainBulletins = getMainBulletins(queryFilter);
		} else {
			queryFilter.addFilter("manageOrg", manageOrg, MatchType.EQ);
			mainBulletins = getMainBulletins(queryFilter);
			//1 代表该时间段检查/整改文件已经上传了
			for (MainBulletin mainBulletin : mainBulletins) {
				for (int i = 0; i < timeData.length; i++) {
					if (timeData[i+1].compareTo(mainBulletin.getBullentinYear()) >= 0 && timeData[i].compareTo(mainBulletin.getBullentinYear()) < 0) {
						if (timeResult.size() <= i) {
							timeResult.add("1");
						}
						if ("0".equals(timeResult.get(i))) {
							timeResult.set(i, "1");
						}
						break; 
					} else {
						if (timeResult.size() <= i) {
							timeResult.add("0");
						}
					}
				}
			}
			double sum = 0;
			for (int i = 0; i < timeResult.size(); i = i + 2) {
				if (timeResult.get(i).equals(timeResult.get(i+1)) && "1".equals(timeResult.get(i))) {
					sum = MathsUtils.sumDouble(sum, yearFull);
				} else if (timeResult.get(i).equals(timeResult.get(i+1)) && "0".equals(timeResult.get(i))) {
					sum = MathsUtils.sumDouble(sum, 0);
				} else {
					sum = MathsUtils.sumDouble(sum, yearPart);
				}
			}
			map.put("timeResult", timeResult);
//			total = 3*yearFull*yearLength+sum;
			total = MathsUtils.formatDouble(MathsUtils.sumDouble(3*yearFull*yearLength, sum), 2);
			//三个单位默认算满分
			map.put("sum", total);
			percentage = MathsUtils.divDouble(sum*100, yearFull*yearLength, 2);
			map.put("percent", percentage);
			
			values.add(manageOrg);
		}	
		
		//只有当系统完善度和检查得分不相等的情况下才更新数据  避免每次搜索都更新数据
		//页面初始化时   属性为null  会导致空指针异常
		checkTableService.updateCheckTable(checkTable, percentage, total, tableFull, values);
		map.put("manageData", mainBulletins);
		map.put("score", checkTable.getTestFull());
		map.put("checkTable", checkTable);
		map.put("years", years);
		map.put("timeResult", timeResult);
		map.put("manageOrg", manageOrg);
		return map;
	}
	
	

}
